from django.shortcuts import render

# Create your views here.
import csv
import os
from django.shortcuts import render
from django.http import JsonResponse

CSV_FILE_PATH = 'db.csv'

def read_csv():
    # print("===>>read_csv")
    data = {}
    if os.path.exists(CSV_FILE_PATH):
        print(os.path.exists(CSV_FILE_PATH))
        with open(CSV_FILE_PATH, mode='r', encoding='utf-8') as file:
            reader = csv.reader(file)
            for row in reader:
                print("len(row):" + str(len(row)))
                if len(row) >= 2:
                    data[row[0]] = row[1]
    # print("data:" + str(data))
    return data

def index(request):
    return render(request, 'index.html')

def search(request):
    print("===>>search")
    keyword = request.GET.get('keyword', '')
    data = read_csv()
    suggestions = [key for key in data.keys() if keyword in key][:10]
    return JsonResponse(suggestions, safe=False)

def get_value(request):
    key = request.GET.get('key', '')
    data = read_csv()
    value = data.get(key, None)
    return JsonResponse({'value': value})

def add_entry(request):
    if request.method == 'POST':
        key = request.POST.get('key', '')
        value = request.POST.get('value', '')
        with open(CSV_FILE_PATH, mode='a', encoding='utf-8', newline='') as file:
            writer = csv.writer(file)
            writer.writerow([key, value])
        return JsonResponse({'status': 'success'})
    return JsonResponse({'status': 'fail'})

